/*   
 * Copyright 2009-2010 Rob Schoening
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *    http://www.apache.org/licenses/LICENSE-2.0
 *    
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.fortasoft.hatfield.util.xml;

import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

import javax.xml.XMLConstants;
import javax.xml.namespace.NamespaceContext;
import javax.xml.xpath.XPath;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class NamespaceContextRegistry implements NamespaceContext {

    private Logger log = LoggerFactory
            .getLogger(NamespaceContextRegistry.class);
    private Map<String, String> nsmap = new ConcurrentHashMap<String, String>();
    private List<NamespaceContext> contextSet = new CopyOnWriteArrayList<NamespaceContext>();

    public void attach(XPath xpath) {
        xpath.setNamespaceContext(this);
    }

    public void attach(XPathUtil xpath) {
        xpath.getXPath().setNamespaceContext(this);
    }

    public void addNamespace(String prefix, String url) {
        nsmap.put(prefix, url);
    }

    public void addNamespaceContext(NamespaceContext nsc) {
        if (nsc == null) {
            return;
        } else {
            contextSet.add(nsc);
        }
    }

    public String getNamespaceURI(String prefix) {
        HashSet<NamespaceContext> set = new HashSet<NamespaceContext>();
        return getNamespaceURI(prefix, set);
    }

    private String getNamespaceURI(String prefix, Set<NamespaceContext> checked) {

        log.debug("Looking up prefix: {}", prefix);
        String ns = nsmap.get(prefix);
        if (prefix == null) {

            throw new NullPointerException("Null prefix");

        } else if (ns != null) {

            log.debug("found: " + ns);
            return ns;

        }

        else if ("xml".equals(prefix)) {
            return XMLConstants.XML_NS_URI;
        }
        checked.add(this);
        for (NamespaceContext ctx : contextSet) {
            if (ctx != this && !checked.contains(ctx)) {
                if (ctx instanceof NamespaceContextRegistry) {
                    ns = ((NamespaceContextRegistry) ctx).getNamespaceURI(
                            prefix, checked);
                } else {
                    ns = ctx.getNamespaceURI(prefix);
                }
                if (ns != null && !ns.equals(XMLConstants.NULL_NS_URI)) {

                    return ns;
                }

            }
        }
        return XMLConstants.NULL_NS_URI;
    }

    public String getPrefix(String namespaceURI) {
        throw new UnsupportedOperationException();
    }

    public Iterator getPrefixes(String namespaceURI) {
        throw new UnsupportedOperationException();
    }

    /**
     * Sets prefix-&gt;namespaceURI mapping. This is intended to be used by
     * Spring. It does *NOT* have a corresponding getter.
     * 
     * @param map
     *            Map of prefix -&gt; namespaceURI pairs
     */
    public void setNamespaceMap(Map<String, String> map) {
        for (Map.Entry<String, String> entry : map.entrySet()) {
            nsmap.put(entry.getKey(), entry.getValue());
        }
    }

}
